package cn.dansj.service.Impl;

import cn.dansj.service.SettingService;
import cn.dansj.entity.Setting;
import cn.dansj.repository.SettingRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
public class SettingServiceImpl implements SettingService {
    private final SettingRepository settingRepository;

    public SettingServiceImpl(SettingRepository settingRepository) {
        this.settingRepository = settingRepository;
    }

    public List<String> getTitle() {
        return settingRepository.getTitle();
    }

    public List<Setting> getAllByClassCode(String classCode) {
        return settingRepository.findAllByClassCodeOrderByRn(classCode);
    }

    @Override
    public List<Setting> getAll() {
        return settingRepository.allSetting();
    }

    public Setting getBySequence(String sequence) {
        return settingRepository.findBySequence(sequence);
    }

    public void save(Setting setting) {
        settingRepository.save(setting);
    }

    public int save(List<Setting> settings) {
        return settingRepository.saveAll(settings).size();
    }

    @Override
    @Transactional
    public void updateSort(String sequence, String rn) {
        settingRepository.updateSort(sequence, rn);
    }

    @Override
    @Transactional
    public void updateSort(List<Map<String, String>> settings) {
        for (Map<String, String> setting : settings) {
            settingRepository.updateSort(setting.get("sequence"), setting.get("rn"));
        }
    }

    @Override
    public Setting getByClassCodeAndName(String classCode, String name) {
        return settingRepository.findByClassCodeAndName(classCode, name);
    }

    @Override
    public int countByClassCodeAndName(String classCode, String name) {
        return settingRepository.countByClassCodeAndName(classCode, name);
    }

    @Override
    public int getMaxRN(String classCode) {
        try {
            return settingRepository.getMaxRN(classCode);
        } catch (Exception e) {
            return 0;
        }
    }
}
